// 七牛云文件上传逻辑
import * as qiniu from 'qiniu-js';
import { message } from 'antd';
import request from '../request';
import { getToken } from './tools';

export const uploadFile = (file, key = file.name, options) => {
    // 压缩图片
    return qiniu.compressImage(file, {
        quality: 0.8,
        maxWidh: 800,
        noCompressIfLarger: true,
    }).then((data) => {
        const { dist } = data;
        // 上传压缩后的文件
        return getToken().then((token) => {
            const observable = qiniu.upload(dist, key, token, null, {
                region: qiniu.region.z1
            });
            const subscription = observable.subscribe({
                next(result) {
                    typeof options.onProgress === 'function' && options.onProgress(result);
                },
                complete(res) {
                    // 上传完成
                    typeof options.onSuccess === 'function' && options.onSuccess(res, data);
                },
                error(err) {
                    message.error(`上传文件异常：${err.message}`);
                }
            });
            return subscription;
        }).catch(() => {
            message.error('获取 token 失败 >_<');
        });
    }).catch((err) => {
        console.log('err ===> ', err.message);
    });
};

// 删除
export const deleteFile = (key) => {
    return request.get('/api/delFile', {
        params: { key }
    });
};
